package query;



import java.util.LinkedList;
import java.util.ListIterator;

import document.InvertedIndex;



public class OrOperand extends BinaryOperand 
{
	@Override
	public void processOperands(InvertedIndex i) 
	{
		queryResult = new LinkedList<Integer>();
		
		leftOperand.process(i);
		rightOperand.process(i);
		ListIterator<Integer> itLeft = leftOperand.getResult().listIterator();
		ListIterator<Integer> itRight = rightOperand.getResult().listIterator();

		
		while(itLeft.hasNext() && itRight.hasNext())
		{
			int l = itLeft.next(); 
			int r = itRight.next();
			if(l<r)
			{
				queryResult.add(l);
				itRight.previous();
			}
			else if(r == l)
			{
				queryResult.add(l);
			}
			else
			{
				queryResult.add(r);
				itLeft.previous();
			}
		}
		
		while(itLeft.hasNext())
		{
			queryResult.add(itLeft.next());
		}
		while(itRight.hasNext())
		{
			queryResult.add(itRight.next());
		}
		
	}
	
	
	@Override
	public String getName() {
		String name  = "";
		if(leftOperand!=null) {
			name += leftOperand.getName();
		}
		name += " or ";
		if(rightOperand!=null) {
			name += rightOperand.getName();
		}
		
		return name;
	}


	@Override
	public Query rebuildOptimal(InvertedIndex i) 
	{
		return rebuild(i,"or",new Term.TermAscending());
	}


	@Override
	public Query rebuildWorst(InvertedIndex i) {
		return rebuild(i,"or",new Term.TermDescending());
	}
	

}
